﻿using Core.Language;
using RulesEngine.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.ValidateRules.Lib
{
    /// <summary>
    /// RulesEngine 工厂类
    /// </summary>
    public static class RulesEngineFactory
    {
        //RulesEngine规则验证：参考：https://mp.weixin.qq.com/s/NUYN4IZkfxdbvR6bBQGjRQ 、 https://github.com/microsoft/RulesEngine
        //var rulesEngine = new RulesEngine.RulesEngine(new Workflow[] { RulesEngineFactory.Required });
        //List<RuleResultTree> resultList =  rulesEngine.ExecuteAllRulesAsync(
        //    nameof(BaseWorkflowRules.Required),
        //    new RuleParameter[]
        //    {
        //        new RuleParameter("value",value)
        //    }).Result;
        //foreach (var item in resultList)
        //{
        //    Console.WriteLine("验证成功：{0}，消息：{1}", item.IsSuccess, item.ExceptionMessage);
        //}


        private static readonly object _lock = new object();

        /// <summary>
        /// 基础规则工作流
        /// </summary>
        public static List<Workflow> BaseWorkflow = new List<Workflow>()
        {
            Required()
        };

        /// <summary>
        /// 必填校验
        /// 规则名称："Required"
        /// 入参：value
        /// </summary>
        /// <param name="displayName">显示的字段名称</param>
        /// <returns>
        /// ErrorMessage 默认值为 "值不能为空"
        /// </returns>
        public static Workflow Required(string displayName = "")
        {            
            if (string.IsNullOrEmpty(displayName))
            {
                displayName = "值";
            }
            Workflow workflow = new Workflow()
            {
                WorkflowName = nameof(Required),
                Rules = new List<Rule>()
                    {
                        new Rule()
                        {
                            RuleName = nameof(Required),
                            ErrorMessage = LanguageResource.StringFormatArgs("{0}不能为空",new object?[]{displayName}),
                            RuleExpressionType = RuleExpressionType.LambdaExpression,
                            Expression = " string.IsNullOrWhiteSpace(value) "
                        }
                    }
            };
            return workflow;
        }
    }
}
